//
//  UIImage+ILGUIKit.m
//  LGLibDemo
//
//  Created by zhangtongle-Pro on 2017/9/6.
//  Copyright © 2017年 Happy. All rights reserved.
//

#import "UIImage+ILGUIKit.h"

#import <AVFoundation/AVFoundation.h>

@implementation UIImage (ILGUIKit)

+ (void)load {
    Method originalMethod = class_getClassMethod([self class], @selector(imageNamed:));
    Method swizzledMethod = class_getClassMethod([self class], @selector(ilg_imageNamed:));
    method_exchangeImplementations(originalMethod, swizzledMethod);
}

+ (UIImage *)ilg_imageNamed:(NSString *)name {
    UIImage *image = [self ilg_imageNamed:name];

    if (image) {
        NSLog(@"%@ 加载image成功", self);
    } else {
        NSLog(@"%@ 加载image失败", self);
    }

    return image;
}

- (BOOL)imageHasAlpha:(UIImage *)image
{
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image.CGImage);
    return (alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast);
}
- (NSString *)ilg_imageBase64String:(UIImage *)image
{
    NSData *imageData = nil;
//    NSString *mimeType = nil;
    
//    if ([self imageHasAlpha: image]) {
//        imageData = UIImagePNGRepresentation(image);
//        mimeType = @"image/png";
//    } else {
//        imageData = UIImageJPEGRepresentation(image, 1.0f);
//        mimeType = @"image/jpeg";
//    }
    imageData = UIImageJPEGRepresentation(image, 1.0f);
    
    NSString *baseStr = [imageData base64EncodedStringWithOptions:0];
    // 为了解决在post上传时，一些特殊字符(=或者+)被变成空格，所以做UTF8处理
    NSString *baseString = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                         (CFStringRef)baseStr,
                                                                                         NULL,
                                                                                         CFSTR(":/?#[]@!$&’()*+,;="),
                                                                                         kCFStringEncodingUTF8);
    return baseString;
    
}

- (NSData *)ilg_imageCompress:(CGFloat)targetWidth compression:(CGFloat)compression
{
    CGSize imageSize = self.size;
    
    // 如果图片已经小于给定的最大尺寸，则只压不缩
    if (imageSize.width < targetWidth) {
        return UIImageJPEGRepresentation(self, compression);
    }
    
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    
    CGFloat targetHeight = (targetWidth / width) * height;
    
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [self drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return UIImageJPEGRepresentation(newImage, compression);
}

- (UIImage *)ilg_stretched {
    CGSize size = self.size;
    UIEdgeInsets edgeInsets = UIEdgeInsetsMake(truncf(size.height - 1)/2, truncf(size.width - 1)/2, truncf(size.height - 1)/2, truncf(size.width - 1)/2);
    return [self resizableImageWithCapInsets:edgeInsets];
}

+ (UIImage *)ilg_imageWithColor:(UIColor *)color size:(CGSize)size {
    return  [self imageWithColor:color rect:CGRectMake(0, 0, size.width, size.height)];
}
+ (UIImage *)ilg_imageWithHexColor:(NSString *)hexColor size:(CGSize)size {
    return [self imageWithColor:[UIColor ilg_colorWithHexString:hexColor] rect:CGRectMake(0, 0, size.width, size.height)];
}
+ (UIImage *)imageWithColor:(UIColor *)color rect:(CGRect)rect {
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return theImage;
}

+ (UIImage *)ilg_screenShotImageForVideo:(NSString *)filePath {
    UIImage *shotImage = nil;
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:fileURL options:nil];
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    shotImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return shotImage;
}

@end
